<template>
  <div class="app-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">
        <el-icon class="title-icon"><Share /></el-icon>
        优惠券发放管理
      </h2>
      <p class="page-description">选择优惠券并指定发放对象，系统将自动处理发放流程</p>
    </div>

    <!-- 发放表单卡片 -->
    <el-card class="distribution-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-content">
            <el-icon class="header-icon"><Share /></el-icon>
            <span class="header-title">优惠券发放配置</span>
          </div>
          <el-tag type="info" size="small">请仔细核对发放信息</el-tag>
        </div>
      </template>

      <!-- 发放表单 -->
      <el-form ref="distributionFormRef" :model="distributionForm" :rules="distributionRules" label-width="120px" class="distribution-form">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="选择优惠券" prop="couponId">
              <el-select
                v-model="distributionForm.couponId"
                placeholder="请选择要发放的优惠券"
                style="width: 100%"
                size="large"
                filterable
              >
                <el-option
                  v-for="coupon in activeCoupons"
                  :key="coupon.id"
                  :label="`${coupon.title} (¥${coupon.amount})`"
                  :value="coupon.id"
                >
                  <div class="coupon-option">
                    <div class="coupon-info">
                      <span class="coupon-title">{{ coupon.title }}</span>
                      <span class="coupon-desc">{{ coupon.description }}</span>
                    </div>
                    <div class="coupon-amount">
                      <el-tag type="danger" size="small">¥{{ coupon.amount }}</el-tag>
                    </div>
                  </div>
                </el-option>
              </el-select>
              <div class="form-tip">
                <el-icon><InfoFilled /></el-icon>
                只显示已激活的优惠券
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发放类型" prop="distributionType">
              <el-radio-group v-model="distributionForm.distributionType" size="large">
                <el-radio-button :label="1">
                  <el-icon><User /></el-icon>
                  指定用户
                </el-radio-button>
                <el-radio-button :label="2">
                  <el-icon><UserFilled /></el-icon>
                  全部用户
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="发放备注">
          <el-input
            v-model="distributionForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入发放备注，如：新用户注册奖励、活动促销等（可选）"
            maxlength="200"
            show-word-limit
            size="large"
          />
        </el-form-item>

        <el-form-item class="form-actions">
          <el-button
            type="primary"
            size="large"
            :loading="distributing"
            @click="handleDistribute"
            :icon="Share"
            class="distribute-btn"
          >
            {{ distributing ? '发放中...' : '立即发放优惠券' }}
          </el-button>
          <el-button size="large" @click="resetForm" :icon="RefreshRight">
            重置表单
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户选择表格 (仅在指定用户时显示) -->
    <el-card class="box-card" v-if="distributionForm.distributionType === 1" style="margin-top: 20px">
      <template #header>
        <div class="card-header">
          <span>选择用户</span>
          <div>
            <el-button size="small" @click="selectAll">全选</el-button>
            <el-button size="small" @click="clearSelection">清空</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索条件 -->
      <el-form :model="userQuery" :inline="true" class="demo-form-inline">
        <el-form-item label="手机号">
          <el-input v-model="userQuery.phone" placeholder="请输入手机号" clearable />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="userQuery.nickname" placeholder="请输入昵称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleUserQuery">查询</el-button>
          <el-button @click="resetUserQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 用户表格 -->
      <el-table
        ref="userTableRef"
        :data="userList"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="用户ID" width="100" />
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="nickname" label="昵称" width="120" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="注册时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="userQuery.pageNum"
          v-model:page-size="userQuery.pageSize"
          :total="userTotal"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleUserSizeChange"
          @current-change="handleUserCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Share, User, UserFilled, InfoFilled, RefreshRight } from '@element-plus/icons-vue'
import { getActiveCoupons, getUserList, distributeCoupons } from '@/api/coupon-distribution'

// 响应式数据
const distributionFormRef = ref()
const userTableRef = ref()

// 发放表单
const distributionForm = reactive({
  couponId: null,
  userIds: [],
  distributionType: 1,
  remark: ''
})

// 表单验证规则
const distributionRules = {
  couponId: [
    { required: true, message: '请选择优惠券', trigger: 'change' }
  ],
  distributionType: [
    { required: true, message: '请选择发放类型', trigger: 'change' }
  ]
}

// 用户查询条件
const userQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  phone: '',
  nickname: '',
  status: 1
})

// 数据
const activeCoupons = ref([])
const userList = ref([])
const userTotal = ref(0)
const selectedUsers = ref([])
const distributing = ref(false)

// 获取激活的优惠券列表
const getActiveCouponList = async () => {
  try {
    const response = await getActiveCoupons()
    if (response.code === 200) {
      activeCoupons.value = response.data
    } else {
      ElMessage.error(response.msg || '获取优惠券列表失败')
    }
  } catch (error) {
    console.error('获取优惠券列表失败:', error)
    ElMessage.error('获取优惠券列表失败')
  }
}

// 获取用户列表
const getUserListData = async () => {
  try {
    const response = await getUserList(userQuery)
    if (response.code === 200) {
      userList.value = response.data.records || response.data.list || []
      userTotal.value = response.data.total || 0
    } else {
      ElMessage.error(response.msg || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  }
}

// 查询用户
const handleUserQuery = () => {
  userQuery.pageNum = 1
  getUserListData()
}

// 重置用户查询
const resetUserQuery = () => {
  userQuery.pageNum = 1
  userQuery.pageSize = 10
  userQuery.phone = ''
  userQuery.nickname = ''
  getUserListData()
}

// 用户分页大小变化
const handleUserSizeChange = (val) => {
  userQuery.pageSize = val
  userQuery.pageNum = 1
  getUserListData()
}

// 用户页码变化
const handleUserCurrentChange = (val) => {
  userQuery.pageNum = val
  getUserListData()
}

// 用户选择变化
const handleSelectionChange = (selection) => {
  selectedUsers.value = selection
  distributionForm.userIds = selection.map(user => user.id)
}

// 全选
const selectAll = () => {
  userTableRef.value.toggleAllSelection()
}

// 清空选择
const clearSelection = () => {
  userTableRef.value.clearSelection()
}

// 发放优惠券
const handleDistribute = async () => {
  try {
    await distributionFormRef.value.validate()
    
    if (distributionForm.distributionType === 1 && distributionForm.userIds.length === 0) {
      ElMessage.warning('请选择要发放的用户')
      return
    }

    const confirmMessage = distributionForm.distributionType === 1 
      ? `确定要向 ${distributionForm.userIds.length} 个用户发放优惠券吗？`
      : '确定要向所有用户发放优惠券吗？'

    await ElMessageBox.confirm(confirmMessage, '确认发放', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    distributing.value = true
    const response = await distributeCoupons(distributionForm)
    
    if (response.code === 200) {
      ElMessage.success(response.msg || '发放成功')
      resetForm()
    } else {
      ElMessage.error(response.msg || '发放失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('发放优惠券失败:', error)
      ElMessage.error('发放失败')
    }
  } finally {
    distributing.value = false
  }
}

// 重置表单
const resetForm = () => {
  distributionFormRef.value.resetFields()
  distributionForm.userIds = []
  selectedUsers.value = []
  userTableRef.value?.clearSelection()
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 初始化
onMounted(() => {
  getActiveCouponList()
  getUserListData()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

/* 页面标题样式 */
.page-header {
  margin-bottom: 24px;
  padding: 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  color: white;
  text-align: center;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
}

.title-icon {
  font-size: 32px;
}

.page-description {
  margin: 0;
  font-size: 16px;
  opacity: 0.9;
}

/* 发放卡片样式 */
.distribution-card {
  border-radius: 12px;
  border: none;
  margin-bottom: 24px;
}

.distribution-card :deep(.el-card__header) {
  background: #fafbfc;
  border-bottom: 1px solid #e4e7ed;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-icon {
  font-size: 20px;
  color: #409eff;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

/* 表单样式 */
.distribution-form {
  padding: 24px 0;
}

.distribution-form .el-form-item {
  margin-bottom: 24px;
}

.distribution-form .el-form-item__label {
  font-weight: 600;
  color: #303133;
}

/* 优惠券选项样式 */
.coupon-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 8px 0;
}

.coupon-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.coupon-title {
  font-weight: 600;
  color: #303133;
}

.coupon-desc {
  font-size: 12px;
  color: #909399;
}

.coupon-amount {
  flex-shrink: 0;
}

/* 表单提示样式 */
.form-tip {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}

/* 单选按钮组样式 */
.el-radio-group .el-radio-button {
  margin-right: 12px;
}

.el-radio-group .el-radio-button :deep(.el-radio-button__inner) {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 12px 20px;
  border-radius: 8px;
}

/* 操作按钮样式 */
.form-actions {
  margin-top: 32px;
  text-align: center;
}

.distribute-btn {
  padding: 12px 32px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 8px;
  background: linear-gradient(135deg, #409eff 0%, #36a3f7 100%);
  border: none;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  transition: all 0.3s ease;
}

.distribute-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(64, 158, 255, 0.4);
}

/* 用户表格卡片样式 */
.box-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.box-card :deep(.el-card__header) {
  background: #fafbfc;
  border-bottom: 1px solid #e4e7ed;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.demo-form-inline .el-form-item {
  margin-right: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-container {
    padding: 12px;
  }

  .page-header {
    padding: 16px;
  }

  .page-title {
    font-size: 24px;
  }

  .distribution-form {
    padding: 16px 0;
  }
}
</style>
